package com.gamutsoft.amb.common.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gamutsoft.amb.common.constants.Constants;
import com.gamutsoft.amb.user.model.SystemUser;


public class CookieUtil {
   /**
    * 同步到cookie保存用户名和加密的密码
    */
   public static void addCookiesUser(HttpServletResponse response,String username,String password){
	   //保存用户名
	   Cookie usernameCookie = new Cookie(Constants.COOKIE_USERNAME, username);
	   usernameCookie.setPath("/");
	   usernameCookie.setSecure(false);
	   usernameCookie.setMaxAge(60*60*24*365*2);//两年
	   response.addCookie(usernameCookie);
	   //保存密码
	   Cookie passwordCookie = new Cookie(Constants.COOKIE_PASSWORD, password);
	   passwordCookie.setPath("/");
	   passwordCookie.setSecure(false);
	   passwordCookie.setMaxAge(60*60*24*365*2);//两年
	   response.addCookie(passwordCookie);
	   
   }
  /**
   * 查找cookie中的用户
   */
   public static SystemUser searchCookiesUser(HttpServletRequest request){
	   String username="";
	   String password="";
	   Cookie cookies[]=request.getCookies();
	   Cookie sCookie=null;
	   SystemUser doamin=null;
	   //查找用户名
	   if(cookies!=null){//cookie不为null
			for(int i=0;i<cookies.length;i++){
				sCookie=cookies[i];					
				if (sCookie.getName().equals(Constants.COOKIE_USERNAME)){
					username = sCookie.getValue();
				}else if(sCookie.getName().equals(Constants.COOKIE_PASSWORD)){
					password = sCookie.getValue();
				}			
			}
		}
	   if(username!=null && !"".equals(username)&& password!=null && !"".equals(password)){
		   doamin=new SystemUser();
		   if(username.indexOf("@")!=-1){
			   doamin.setEmail(username);
		   }else{
			   doamin.setUsername(username);
		   }
		   doamin.setPassword(password);
	   }
	   
	   return doamin;
   }
   /**
    * 清除cookie信息
    * @param request
    * @return
    */
   public static void deleteCookiesUser(HttpServletRequest request,HttpServletResponse response){
	   Cookie cookies[]=request.getCookies();
	   Cookie sCookie=null;
	   //查找用户名
	   if(cookies!=null){//cookie不为null
			for(int i=0;i<cookies.length;i++){
				sCookie=cookies[i];					
				if (sCookie.getName().equals(Constants.COOKIE_USERNAME)){
					sCookie.setValue(null);
					sCookie.setMaxAge(0);
				}else if(sCookie.getName().equals(Constants.COOKIE_PASSWORD)){
					sCookie.setValue(null);
					sCookie.setMaxAge(0);
				}	
				response.addCookie(sCookie);
			}
		}
   }
}
